package com.sn.springboot_netty.utils;

import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/***
 * Windows 命令行工具类
 */
public class WinCmdUtil {

    /**
     * 执行单一命令
     * @param cmd 执行的命令
     * @return
     */
    public static String runCmd(String cmd) throws IOException{
        String result = "";
        String error = "";

        Process process = Runtime.getRuntime().exec(cmd);
        InputStream in = process.getInputStream();
        InputStream err = process.getErrorStream();
        result = processStdout(in);
        error = processStdout(err);
        if(!StringUtils.isEmpty(error)){
            return result+error;
        }
        return result;
    }

    /**
     * 执行组命令
     * @param cmds 执行的命令组
     * @return
     */
    public static String runCmd(String[] cmds) throws IOException{
        String result = "";
        String error = "";

        for (String cmd : cmds) {
            System.out.println("执行命令：" + cmd);
            Process process = Runtime.getRuntime().exec(cmd);
            InputStream in = process.getInputStream();
            InputStream err = process.getErrorStream();
            result = processStdout(in);
            error = processStdout(err);
            if(!StringUtils.isEmpty(error)){
                result = result + error;
                break;
            }
            result += result;
        }
        return result;
    }

    /**
     * 解析命令行返回数据
     * @return
     */
    private static String processStdout(InputStream in) throws IOException {
        String strLine = ""; //行数据
        StringBuffer result = new StringBuffer(); //结果集

        InputStreamReader is = new InputStreamReader(in,"gbk");
        BufferedReader buffer = new BufferedReader(is);
        try {
            while (null != (strLine = buffer.readLine())){
                if(StringUtils.isEmpty(strLine)){
                    result.append(strLine);
                    continue;
                }
                result.append("\n");
                result.append(strLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            buffer.close();
            is.close();
        }

        return result.toString();

    }

    public static void main(String[] args) throws IOException {
        String cmd = "ping 127.0.0.1";
        String[] cmds = {"ping 127.0.0.1","telnet 39.99.165.179 57201"};
        String result = runCmd(cmds);

        System.out.println(result);
    }

}
